package org.dbstar.scheduler.control.db;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;

import org.apache.commons.io.IOUtils;
import org.springframework.jdbc.support.SqlValue;

/**
 * 用于设置Blob值的SqlValue
 * 
 * @author 代波
 * @since 1.0.0
 * @version 1.0.0
 * @date 2012-4-25
 */
public class BlobSqlValue implements SqlValue {
	private InputStream in;

	public BlobSqlValue(Object object) throws IOException {
		if (object == null) {
			in = null;
		} else {
			ByteArrayOutputStream bo = new ByteArrayOutputStream();
			ObjectOutputStream o = new ObjectOutputStream(bo);
			try {
				o.writeObject(object);
			} finally {
				IOUtils.closeQuietly(o);
			}
			in = new ByteArrayInputStream(bo.toByteArray());
		}
	}

	@Override
	public void setValue(PreparedStatement ps, int paramIndex) throws SQLException {
		if (in == null) {
			ps.setNull(paramIndex, Types.BLOB);
		} else {
			ps.setBlob(paramIndex, in);
		}
	}

	@Override
	public void cleanup() {
		IOUtils.closeQuietly(in);
		in = null;
	}
}
